package com.aaa.mrcai.service.impl;

import com.aaa.mrcai.mapper.AdminLoginMapper;
import com.aaa.mrcai.mapper.PermissionMapper;
import com.aaa.mrcai.pojo.entity.AdminLogin;
import com.aaa.mrcai.pojo.entity.EmpInfo;
import com.aaa.mrcai.pojo.entity.Permission;
import com.aaa.mrcai.result.AjaxResult;
import com.aaa.mrcai.service.SysService;
import com.aaa.mrcai.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:Li-Yan-Chun
 * @Date:2021/12/2 16:53
 */
@Service
public class SysServiceImpl implements SysService {

    @Autowired
    private  AdminLoginMapper adminLoginMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private HttpSession session;

    @Override
    public AjaxResult login(String adminname, String password) {
        AdminLogin adminLogin = adminLoginMapper.adminLogin(adminname, password);
        //登录失败
        if(adminLogin==null){
            return  AjaxResult.defeated("账号或密码错误");
        }
        if(adminLogin.getState()==1){
            return AjaxResult.defeated("员工离职");
        }
        if(adminLogin.getState()==2){
            return AjaxResult.defeated("员工账号被冻结，请找管理员");
        }
        //登录成功后，将管理员的信息(部门、角色等)存入session
        EmpInfo emp = adminLoginMapper.getAdminById(adminLogin.getEid());
        session.setAttribute("emp",emp);
        System.out.println(emp);
        return AjaxResult.success(emp);
    }

    @Override
    public AjaxResult getInfo() {
        EmpInfo emp = (EmpInfo) session.getAttribute("emp");
        Map<String, Object> map = new HashMap<>();
        map.put("empInfo",emp);
        Integer id = emp.getEmpRole().getId();
        if(id == 1){
            List<Permission> adminPers = permissionMapper.getAdminPers();
            map.put("permission",adminPers);
        }else {
            List<Permission> commentPers = permissionMapper.getCommentPers(id);
            List<Permission> permissions = PermissionUtil.handlePermission(commentPers);
            map.put("permission",permissions);
        }
        return AjaxResult.success(map);
    }

    @Override
    public void logout() {

        //servletContext.removeAttribute("user");

        session.invalidate();
    }
}
